<template>
	<div class="ocr-recognition">
		<!-- 主内容区域 -->
		<div class="main-content">
			<!-- 上传区域 -->
			<div class="upload-section">
				<div class="search-form-capsule">
					<div class="capsule-row">
						<!-- 文件上传 -->
						<div class="capsule-item">
							<el-icon class="capsule-icon"><Upload /></el-icon>
							<span class="capsule-label">文件</span>
							<el-upload
								ref="uploadRef"
								:auto-upload="false"
								:limit="1"
								:on-change="handleFileChange"
								:on-remove="handleFileRemove"
								accept=".pdf,.jpg,.jpeg,.png,.bmp,.tiff,.gif"
								class="capsule-input"
							>
								<template #trigger>
									<el-button type="primary" size="small" :icon="Upload">
										选择文件
									</el-button>
								</template>
							</el-upload>
						</div>

						<!-- 文件类型显示 -->
						<div class="capsule-item" v-if="selectedFile">
							<el-icon class="capsule-icon"><Document /></el-icon>
							<span class="capsule-label">类型</span>
							<span class="file-type-text">{{ fileTypeText }}</span>
						</div>

						<!-- 识别按钮 -->
						<div class="capsule-item capsule-action-group">
							<div
								class="action-button"
								:class="{ 'is-active': isProcessing }"
								:disabled="!selectedFile || isProcessing"
								@click="handleRecognize"
							>
								<el-icon class="action-icon">
									<Loading v-if="isProcessing" />
									<Search v-else />
								</el-icon>
								<span class="action-label">{{ isProcessing ? '识别中...' : '开始识别' }}</span>
							</div>
							<div class="button-group-divider"></div>
							<div
								class="action-button"
								@click="handleClear"
							>
								<el-icon class="action-icon"><Refresh /></el-icon>
								<span class="action-label">清空</span>
							</div>
						</div>
					</div>
				</div>
			</div>

			<!-- 加载状态 -->
			<div class="loading-section" v-if="isProcessing">
				<el-icon class="loading-icon"><Loading /></el-icon>
				<p class="loading-text">正在识别中，请稍候...</p>
			</div>

			<!-- 结果展示区域 -->
			<div class="result-section" v-else-if="ocrTexts.length > 0 || ocrImages.length > 0">
				<!-- OCR识别文本 -->
				<div class="result-content" v-if="ocrTexts.length > 0">
					<div class="section-title">
						<el-icon><DocumentCopy /></el-icon>
						<span>识别文本</span>
					</div>
					<div class="text-container">
						<div class="text-item" v-for="(text, index) in ocrTexts" :key="index">
							{{ text }}
						</div>
					</div>
				</div>

				<!-- OCR结果图片 -->
				<div class="result-content" v-if="ocrImages.length > 0">
					<div class="section-title">
						<el-icon><Picture /></el-icon>
						<span>识别结果图片 ({{ ocrImages.length }})</span>
					</div>
					<div class="image-container">
						<div class="image-item" v-for="(image, index) in ocrImages" :key="index">
							<el-image
								:src="image"
								:alt="`OCR结果图片 ${index + 1}`"
								:preview-src-list="ocrImages"
								:initial-index="index"
								preview-teleported
								fit="contain"
								class="ocr-result-image"
								lazy
							>
								<template #error>
									<div class="image-error">
										<el-icon><Picture /></el-icon>
										<span>图片加载失败</span>
									</div>
								</template>
							</el-image>
							<div class="image-label">图片 {{ index + 1 }}</div>
						</div>
					</div>
				</div>
			</div>

			<!-- 空状态 -->
			<div class="empty-section" v-else>
				<el-empty description="请上传图片或PDF文件进行OCR识别" />
			</div>
		</div>
	</div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { ElMessage, ElUpload, ElImage, UploadFile } from 'element-plus';
import { Document, DocumentCopy, Loading, Picture, Refresh, Search, Upload } from '@element-plus/icons-vue';
import { useOcrApi } from '/@/api/ocr';

// API
const ocrApi = useOcrApi();
const uploadRef = ref();

// 响应式数据
const selectedFile = ref<File | null>(null);
const isProcessing = ref(false);
const ocrResult = ref<any>(null);
const ocrTexts = ref<string[]>([]);
const ocrImages = ref<string[]>([]);

// 计算属性
const fileTypeText = computed(() => {
	if (!selectedFile.value) return '';
	const fileName = selectedFile.value.name.toLowerCase();
	if (fileName.endsWith('.pdf')) {
		return 'PDF文档';
	}
	return '图像文件';
});

// 根据文件后缀判断文件类型
const getFileType = (fileName: string): number => {
	const lowerName = fileName.toLowerCase();
	if (lowerName.endsWith('.pdf')) {
		return 0; // PDF
	}
	return 1; // 图像
};

// 将文件转换为Base64
const fileToBase64 = (file: File): Promise<string> => {
	return new Promise((resolve, reject) => {
		const reader = new FileReader();
		reader.onload = () => {
			const result = reader.result as string;
			// 移除 data:image/...;base64, 前缀（如果有）
			const base64 = result.includes(',') ? result.split(',')[1] : result;
			resolve(base64);
		};
		reader.onerror = reject;
		reader.readAsDataURL(file);
	});
};

// 处理文件变化
const handleFileChange = (file: UploadFile) => {
	if (file.raw) {
		selectedFile.value = file.raw;
		// 清空之前的结果
		clearResults();
	}
};

// 处理文件移除
const handleFileRemove = () => {
	selectedFile.value = null;
	clearResults();
};

// 清空结果
const clearResults = () => {
	ocrResult.value = null;
	ocrTexts.value = [];
	ocrImages.value = [];
};

// 提取OCR识别文本
const extractOcrTexts = (resultData: any): string[] => {
	const texts: string[] = [];
	
	// 递归查找 ocrResults
	const extractFromObject = (obj: any) => {
		if (!obj || typeof obj !== 'object') return;
		
		// 检查 ocrResults 字段
		if (Array.isArray(obj.ocrResults)) {
			obj.ocrResults.forEach((item: any) => {
				const pruned = item.prunedResult || item;
				if (Array.isArray(pruned.rec_texts)) {
					texts.push(...pruned.rec_texts);
				}
			});
		}
		
		// 递归检查其他字段
		for (const key in obj) {
			if (obj.hasOwnProperty(key) && typeof obj[key] === 'object') {
				extractFromObject(obj[key]);
			}
		}
	};
	
	if (Array.isArray(resultData)) {
		resultData.forEach(item => extractFromObject(item));
	} else {
		extractFromObject(resultData);
	}
	
	return texts;
};

// 提取OCR结果图片
const extractOcrImages = (resultData: any): string[] => {
	const images: string[] = [];
	
	// 递归查找 ocrImage
	const extractFromObject = (obj: any) => {
		if (!obj || typeof obj !== 'object') return;
		
		// 检查 ocrResults 数组中的 ocrImage
		if (Array.isArray(obj.ocrResults)) {
			obj.ocrResults.forEach((item: any) => {
				if (item.ocrImage) {
					images.push(`data:image/jpeg;base64,${item.ocrImage}`);
				}
			});
		}
		
		// 递归检查其他字段
		for (const key in obj) {
			if (obj.hasOwnProperty(key) && typeof obj[key] === 'object') {
				extractFromObject(obj[key]);
			}
		}
	};
	
	if (Array.isArray(resultData)) {
		resultData.forEach(item => extractFromObject(item));
	} else {
		extractFromObject(resultData);
	}
	
	return images;
};

// 处理识别
const handleRecognize = async () => {
	if (!selectedFile.value) {
		ElMessage.warning('请先选择文件');
		return;
	}

	isProcessing.value = true;
	clearResults();

	try {
		// 将文件转换为Base64
		const base64Data = await fileToBase64(selectedFile.value);
		
		// 根据文件后缀判断类型
		const fileType = getFileType(selectedFile.value.name);
		
		// 调用OCR接口
		const result = await ocrApi.callOcr(base64Data, fileType, true);
		
		ocrResult.value = result;
		
		// 提取识别文本
		ocrTexts.value = extractOcrTexts(result);
		
		// 提取结果图片
		ocrImages.value = extractOcrImages(result);
		
		if (ocrTexts.value.length === 0 && ocrImages.value.length === 0) {
			ElMessage.warning('未识别到文本或图片');
		} else {
			ElMessage.success('识别完成');
		}
	} catch (error: any) {
		console.error('OCR识别失败:', error);
		ElMessage.error(error?.response?.data?.msg || error?.message || '识别失败，请重试');
		clearResults();
	} finally {
		isProcessing.value = false;
	}
};

// 处理清空
const handleClear = () => {
	selectedFile.value = null;
	clearResults();
	uploadRef.value?.clearFiles();
	ElMessage.info('已清空');
};
</script>

<style scoped lang="scss">
.ocr-recognition {
	padding: 20px;
	height: 100%;
	overflow-y: auto;
}

.main-content {
	max-width: 1400px;
	margin: 0 auto;
}

/* 上传区域 */
.upload-section {
	margin-bottom: 24px;
}

.search-form-capsule {
	background: rgba(248, 249, 250, 0.8);
	backdrop-filter: blur(10px);
	border: 1px solid rgba(139, 149, 167, 0.15);
	border-radius: 20px;
	padding: 16px;
}

.capsule-row {
	display: grid;
	grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
	gap: 12px;
	align-items: center;
}

.capsule-item {
	display: flex;
	align-items: center;
	gap: 6px;
	padding: 8px 12px;
	border-radius: 18px;
	background: rgba(255, 255, 255, 0.7);
	backdrop-filter: blur(10px);
	border: 1px solid rgba(139, 149, 167, 0.15);
	transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
	font-family: inherit;
	min-height: 40px;
	box-sizing: border-box;
	flex-shrink: 0;
}

.capsule-item:hover {
	background: rgba(255, 255, 255, 0.85);
	border-color: rgba(107, 124, 150, 0.25);
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.capsule-icon {
	font-size: 16px;
	color: #8b95a7;
	opacity: 0.8;
	transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
	flex-shrink: 0;
	width: 16px;
	display: flex;
	align-items: center;
	justify-content: center;
}

.capsule-item:hover .capsule-icon {
	color: #6b7c96;
	opacity: 1;
}

.capsule-label {
	font-size: 0.875rem;
	font-weight: 500;
	color: #4a5568;
	white-space: nowrap;
	letter-spacing: -0.01em;
	font-feature-settings: 'kern' 1;
	flex-shrink: 0;
	width: 56px;
	text-align: left;
}

.capsule-input {
	flex: 1;
	min-width: 120px;
}

.capsule-input :deep(.el-upload) {
	width: 100%;
}

.capsule-input :deep(.el-button) {
	border: none;
	background: transparent;
	color: #6b7c96;
	padding: 0;
}

.file-type-text {
	font-size: 0.875rem;
	color: #6b7c96;
	font-weight: 500;
}

/* 操作按钮组 */
.capsule-action-group {
	display: flex;
	gap: 0;
	padding: 0;
	background: rgba(248, 249, 250, 0.8);
	border: 1px solid rgba(139, 149, 167, 0.15);
}

.button-group-divider {
	width: 1px;
	background: rgba(139, 149, 167, 0.2);
	margin: 4px 0;
}

.action-button {
	flex: 1;
	display: flex;
	align-items: center;
	justify-content: center;
	gap: 6px;
	padding: 6px 16px;
	border-radius: 18px;
	font-size: 0.8125rem;
	font-weight: 500;
	cursor: pointer;
	user-select: none;
	transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
	border: none;
	background: transparent;
	backdrop-filter: none;
	letter-spacing: -0.01em;
	line-height: 1.4;
	font-feature-settings: 'kern' 1;
	color: #6b7c96;
	height: 100%;
}

.action-button:first-child {
	border-top-left-radius: 18px;
	border-bottom-left-radius: 18px;
	border-top-right-radius: 0;
	border-bottom-right-radius: 0;
}

.action-button:last-child {
	border-top-right-radius: 18px;
	border-bottom-right-radius: 18px;
	border-top-left-radius: 0;
	border-bottom-left-radius: 0;
}

.action-button:hover {
	color: #6b7c96;
	background: rgba(107, 124, 150, 0.08);
}

.action-button.is-active {
	background: rgba(107, 124, 150, 0.85);
	backdrop-filter: blur(10px);
	border-color: transparent;
	color: #ffffff;
	box-shadow: 0 2px 8px rgba(107, 124, 150, 0.2);
	font-weight: 600;
}

.action-button:disabled {
	opacity: 0.5;
	cursor: not-allowed;
}

.action-icon {
	font-size: 14px;
	color: inherit;
	transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
}

.action-label {
	font-size: inherit;
	color: inherit;
	white-space: nowrap;
}

/* 结果展示区域 */
.result-section {
	margin-top: 24px;
}

.result-content {
	background: rgba(255, 255, 255, 0.8);
	backdrop-filter: blur(10px);
	border: 1px solid rgba(139, 149, 167, 0.15);
	border-radius: 20px;
	padding: 24px;
	margin-bottom: 24px;
}

.section-title {
	display: flex;
	align-items: center;
	gap: 8px;
	font-size: 1.125rem;
	font-weight: 600;
	color: #4a5568;
	margin-bottom: 16px;
	letter-spacing: -0.02em;
}

.section-title .el-icon {
	font-size: 18px;
	color: #6b7c96;
}

/* 文本容器 */
.text-container {
	max-height: 400px;
	overflow-y: auto;
	padding: 16px;
	background: rgba(248, 249, 250, 0.6);
	border-radius: 12px;
	border: 1px solid rgba(139, 149, 167, 0.1);
}

.text-item {
	padding: 8px 0;
	font-size: 0.9375rem;
	color: #4a5568;
	line-height: 1.6;
	border-bottom: 1px solid rgba(139, 149, 167, 0.1);
}

.text-item:last-child {
	border-bottom: none;
}

/* 图片容器 */
.image-container {
	display: grid;
	grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
	gap: 20px;
	padding: 16px;
}

.image-item {
	background: rgba(248, 249, 250, 0.6);
	border-radius: 12px;
	padding: 12px;
	border: 1px solid rgba(139, 149, 167, 0.1);
	transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
	display: flex;
	flex-direction: column;
	align-items: stretch;
}

.image-item:hover {
	box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
	transform: translateY(-2px);
}

.ocr-result-image {
	width: 100%;
	height: auto;
	border-radius: 8px;
	display: block;
	cursor: pointer;
	min-height: 200px;
	background: rgba(255, 255, 255, 0.8);
}

.ocr-result-image :deep(.el-image__inner) {
	border-radius: 8px;
	transition: transform 0.3s ease;
}

.ocr-result-image:hover :deep(.el-image__inner) {
	transform: scale(1.02);
}

.image-error {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	min-height: 200px;
	color: #8b95a7;
	gap: 8px;
}

.image-error .el-icon {
	font-size: 48px;
}

.image-label {
	margin-top: 8px;
	text-align: center;
	font-size: 0.8125rem;
	color: #6b7c96;
	font-weight: 500;
}

/* 空状态 */
.empty-section {
	margin-top: 60px;
	text-align: center;
}

/* 加载状态 */
.loading-section {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 60px 20px;
	gap: 16px;
}

.loading-icon {
	font-size: 48px;
	color: #6b7c96;
	animation: rotate 1s linear infinite;
}

@keyframes rotate {
	from {
		transform: rotate(0deg);
	}
	to {
		transform: rotate(360deg);
	}
}

.loading-text {
	font-size: 1rem;
	color: #6b7c96;
	font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 768px) {
	.image-container {
		grid-template-columns: 1fr;
	}
	
	.capsule-row {
		flex-direction: column;
	}
	
	.capsule-item {
		width: 100%;
	}
}
</style>
